package cn.org.cute.ebocy.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Array; 

/**
 * JSON 工具类
 * @author xiaolei
 *
 */
public class JsonUtil {
	
	/**
	 * 获得jsonObject对象
	 * @param value json格式的字符串
	 * @return
	 */
	public static JSONObject getJSONObject(String value) {
		JSONObject jsonObject = null;
		if (value == null || "".equals(value) || "null".equals(value) || !value.trim().startsWith("{") || !value.trim().endsWith("}")) {
			return null;
		}

		try {
			jsonObject = new JSONObject(value);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jsonObject;

	}
	
	
	/**
	 * 获得JSONArray对象
	 * @param value json数组格式的字符串
	 * @return
	 */
	public static JSONArray getJSONArray(String value) {
		JSONArray jsonArray = null;
		if (value == null || "".equals(value) || "null".equals(value) || !value.trim().startsWith("[") || !value.trim().endsWith("]")) {
			return jsonArray;
		}

		try {
			jsonArray = new JSONArray(value);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jsonArray;
	}
	
	public static String createJsData(Object obj) {  
        if (null == obj) {  
            return "\"\"";  
        }  
        StringBuffer resultStr = new StringBuffer();  
        if (obj instanceof Collection) {    // 闆嗗悎List銆丼et绛夌被鍨? 
            resultStr.append("[");  
            Collection collection = (Collection) obj;  
            if (collection.size() > 0) {  
                Object[] collectionObj = collection.toArray();  
                for (int i = 0; i < collectionObj.length; i++) {  
                    resultStr.append(createJsData(collectionObj[i]) + ",");  
                }  
                resultStr.deleteCharAt(resultStr.lastIndexOf(","));  
            }  
            resultStr.append("]");  
        } else if (obj instanceof Map) {    // Map绫诲瀷  
            resultStr.append("{");  
            Map map = (Map) obj;  
            if (map.size() > 0) {  
                Iterator<Entry> iter = map.entrySet().iterator();  
                while (iter.hasNext()) {  
                    Map.Entry entry = iter.next();  
                    String key = entry.getKey().toString();  
                    resultStr.append("\"" + key + "\":");    // jquery1.4浠ヤ笂瑕佹眰鍙屽紩鍙峰寘瑁? 
                    Object tempObj = entry.getValue();  
                    resultStr.append(createJsData(tempObj) + ",");  
                }  
                resultStr.deleteCharAt(resultStr.lastIndexOf(","));  
            }  
            resultStr.append("}");  
        } else {    // 鍩烘湰绫诲瀷  
            try {  
                int arrLength = Array.getLength(obj);  
                resultStr.append("[");  
                if (arrLength > 0) {  
                    for (int i = 0; i < arrLength; i++) {  
                        resultStr.append(createJsData(Array.get(obj, i)) + ",");  
                    }  
                    resultStr.deleteCharAt(resultStr.lastIndexOf(","));  
                }  
                resultStr.append("]");  
            } catch (IllegalArgumentException e) {    // 涓嶆槸鏁扮粍锛屾槸鏈€鍩烘湰鐨勬暟鎹? 
                resultStr.append("\"" + stringToJson(obj + "") + "\"");  
            }  
        }  
        return resultStr.toString();  
    }  
	
	
	public static String stringToJson(String str) {  
        StringBuffer sb = new StringBuffer();  
        for (int i = 0; i < str.length(); i++) {  
            char c = str.charAt(i);  
            switch (c) {  
                case '\"':  
                    sb.append("\\\"");  
                    break;  
                case '\\':  
                    sb.append("\\\\");  
                    break;  
                case '/':  
                    sb.append("\\/");  
                    break;  
                case '\b':  
                    sb.append("\\b");  
                    break;  
                case '\f':  
                    sb.append("\\f");  
                    break;  
                case '\n':  
                    sb.append("\\n");  
                    break;  
                case '\r':  
                    sb.append("\\r");  
                    break;  
                case '\t':  
                    sb.append("\\t");  
                    break;  
                default:  
                    sb.append(c);  
            }  
        }  
        return sb.toString();  
    }  
}
